<template>
  <div>
    <el-drawer v-model="drawer" :title="drawerTitle" :with-header="true">
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="150px"
        class="demo-ruleForm"
      >
        <el-form-item label="收/付款节点名称：" prop="pointName">
          <el-autocomplete
            v-model="ruleForm.pointName"
            :fetch-suggestions="querySearch"
            :trigger-on-focus="true"
            clearable
            class="inline-input w-50"
            placeholder="请输入收/付款节点名称"
            style="width: 280px"
            maxlength="64"
          />
        </el-form-item>
        <el-form-item label="收/付款节点日期：" v-if="!ifAdd">
          <el-date-picker
            v-model="ruleForm.pointTime"
            type="date"
            placeholder="请选择收/付款节点日期"
            format="YYYY/MM/DD"
            value-format="YYYY-MM-DD"
            style="width: 280px"
          />
        </el-form-item>
        <el-form-item label="天数：" prop="dayNumber">
          <el-input-number
            v-model="ruleForm.dayNumber"
            placeholder="请输入天数"
            style="width: 220px"
            :min="0"
          />
        </el-form-item>
        <el-form-item label="收款百分比：" v-if="type === '1'">
          <el-input-number
            v-model="ruleForm.collectionPercent"
            placeholder="请输入收款百分比"
            style="width: 220px"
            :precision="2"
            :min="0"
            :max="100"
          />
          &nbsp;&nbsp;%
        </el-form-item>
        <el-form-item label="收款金额：" v-if="type === '1'" prop="collectionAmount">
          <el-input-number
            v-model="ruleForm.collectionAmount"
            placeholder="请输入收款金额"
            style="width: 220px"
            :precision="2"
            :min="0"
            :max="difference"
          />
          &nbsp;&nbsp;元
        </el-form-item>
        <el-form-item label="付款百分比：" v-if="type === '0'">
          <el-input-number
            v-model="ruleForm.paymentPercent"
            placeholder="请输入付款百分比"
            style="width: 220px"
            :precision="2"
            :min="0"
            :max="100"
          />
          &nbsp;&nbsp;%
        </el-form-item>
        <el-form-item label="付款金额：" v-if="type === '0'" prop="paymentAmount">
          <el-input-number
            v-model="ruleForm.paymentAmount"
            placeholder="请输入付款金额"
            style="width: 220px"
            :precision="2"
            :min="0"
            :max="difference"
          />
          &nbsp;&nbsp;元
        </el-form-item>
        <el-form-item label="备注：" prop="remark">
          <el-input v-model="ruleForm.remark" placeholder="请输入付款备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="drawer = false">取消</el-button>
          <el-button type="primary" @click="handleClose(ruleFormRef)">确定</el-button>
        </span>
      </template>
    </el-drawer>
  </div>
</template>

<script lang="ts" setup>
  import { ref, reactive, nextTick } from 'vue'
  import type { FormInstance } from 'element-plus'
  import { ElMessage } from 'element-plus'
  import { validator } from '@/utils/numberFormat.ts'
  import { getSysPointList } from '@/api/controller/sys-user-controller/index'
  import {
    postCollectionCycle,
    putCollectionCycle,
    getCollectionCycleGetDifferenceByContractId,
  } from '@/api/controller/collection-cycle-controller/index'
  import {
    postPaymentCycle,
    putPaymentCycle,
    getPaymentCycleGetDifferenceByContractId,
  } from '@/api/controller/payment-cycle-controller/index'
  import { add, bignumber, number } from 'mathjs'
  const drawer = ref(false)
  //打开弹窗
  const drawerTitle = ref('')
  const ifAdd = ref(true)
  const difference = ref(null)
  const type = ref()
  const show = async (row, id, ty) => {
    ruleForm.value = {
      pointName: '',
      contractId: id,
      dayNumber: null,
      pointTime: null,
      collectionPercent: null,
      collectionAmount: null,
      paymentPercent: null,
      paymentAmount: null,
      remark: null,
    }
    type.value = ty
    let res
    if (type.value === '1') {
      res = await getCollectionCycleGetDifferenceByContractId({
        contractId: id,
      })
      if (ifAdd.value) {
        difference.value = res.data.differencePrice
      } else {
        difference.value = number(
          add(bignumber(row.collectionAmount), bignumber(res.data.differencePrice)),
        )
      }
    } else {
      res = await getPaymentCycleGetDifferenceByContractId({
        contractId: id,
      })
      if (ifAdd.value) {
        difference.value = res.data.differencePrice
      } else {
        difference.value = number(
          add(bignumber(row.paymentAmount), bignumber(res.data.differencePrice)),
        )
      }
    }
    res = await getSysPointList()
    restaurants.value = res.data
    if (row.id) {
      ruleForm.value = { ...row, ...{ contractId: id } }
      drawerTitle.value = ty === '1' ? '编辑收款方式' : '编辑付款方式'
      ifAdd.value = false
    } else {
      drawerTitle.value = ty === '1' ? '新增收款方式' : '新增付款方式'
      ifAdd.value = true
    }
    drawer.value = true
    nextTick(() => {
      ruleFormRef.value.clearValidate()
    })
  }

  //提交的数据
  const ruleFormRef = ref<FormInstance>()
  const ruleForm = ref({
    pointName: '',
    contractId: null,
    dayNumber: null,
    pointTime: null,
    collectionPercent: null,
    collectionAmount: null,
    paymentPercent: null,
    paymentAmount: null,
    remark: null,
  })
  const rules = reactive({
    pointName: [
      { required: true, message: '请输入收/付款节点名称', trigger: 'blur' },
      { min: 0, max: 64, message: '长度不超过64个字符', trigger: 'blur' },
    ],
    dayNumber: [{ required: true, message: '请选择天数', trigger: 'blur' }],
    collectionAmount: [
      { required: true, message: '请输入收款金额', trigger: 'blur' },
      { validator, trigger: 'blur' },
    ],
    paymentAmount: [
      { required: true, message: '请输入付款金额', trigger: 'blur' },
      { validator, trigger: 'blur' },
    ],
    remark: [{ min: 0, max: 64, message: '长度不超过64个字符', trigger: 'blur' }],
  })

  //提交
  const handleClose = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.validate(async (valid) => {
      if (valid) {
        let result
        if (type.value === '1') {
          if (ifAdd.value) {
            result = await postCollectionCycle(ruleForm.value, { loading: true })
          } else {
            result = await putCollectionCycle(ruleForm.value, { loading: true })
          }
        } else {
          if (ifAdd.value) {
            result = await postPaymentCycle(ruleForm.value, { loading: true })
          } else {
            result = await putPaymentCycle(ruleForm.value, { loading: true })
          }
        }
        if (result.code === 200) {
          await emit('getData')
          drawer.value = false
          ElMessage.success('更新成功')
        }
      } else {
        ElMessage.warning('请正确填写表单')
        return false
      }
    })
  }
  const restaurants = ref([])
  const querySearch = (queryString: string, cb: any) => {
    const results = queryString
      ? restaurants.value.filter((item) => item.value.indexOf(queryString) >= 0)
      : restaurants.value
    // call callback function to return suggestions
    cb(results)
  }

  const emit = defineEmits(['getData'])
  defineExpose({
    show,
  })
</script>
